// Java重构相关导入
import { JavaRefactorAnalyzer } from '../analyzers/JavaRefactorAnalyzer.js';
import { SpringBootRefactorAnalyzer } from '../analyzers/SpringBootRefactorAnalyzer.js';
import { MavenExecutor } from '../executors/MavenExecutor.js';
import { FileAnalyzer } from '../analyzers/FileAnalyzer.js';
import { FileRefactor } from '../refactors/FileRefactor.js';
import { SimpleJava8Optimizer } from '../refactors/SimpleJava8Optimizer.js';
import { AutoRefactorLargeMethod } from '../refactors/AutoRefactorLargeMethod.js';
import { ServiceSplitter } from '../refactors/ServiceSplitter.js';
import { ServiceInterfaceGenerator } from '../refactors/ServiceInterfaceGenerator.js';
import { CrossFileReferenceUpdater } from '../refactors/CrossFileReferenceUpdater.js';
import { PackageMover } from '../refactors/PackageMover.js';
import { MagicValueExtractor } from '../refactors/MagicValueExtractor.js';
import { EnumExtractor } from '../refactors/EnumExtractor.js';
import { SpringBootAnnotationOptimizer } from '../refactors/SpringBootAnnotationOptimizer.js';
import { ParameterObjectRefactor } from '../refactors/ParameterObjectRefactor.js';
import { FieldEncapsulationRefactor } from '../refactors/FieldEncapsulationRefactor.js';
import { AbstractInterfaceExtractor } from '../refactors/AbstractInterfaceExtractor.js';
import { DesignPatternRefactor } from '../refactors/DesignPatternRefactor.js';
import { BuilderPatternRefactor } from '../refactors/BuilderPatternRefactor.js';
import { AIIntegration } from '../ai/AIIntegration.js';
import { InheritanceRefactor } from '../refactors/InheritanceRefactor.js';
import { InlineRefactor } from '../refactors/InlineRefactor.js';
import { ConditionalRefactor } from '../refactors/ConditionalRefactor.js';
import { ExceptionRefactor } from '../refactors/ExceptionRefactor.js';
import { SpringBootConfigRefactor } from '../refactors/SpringBootConfigRefactor.js';

// 前端重构相关导入
import { ReactRefactor } from '../refactors/ReactRefactor.js';
import { VueRefactor } from '../refactors/VueRefactor.js';
import { CSSRefactor } from '../refactors/CSSRefactor.js';
import { JavaScriptModernizer } from '../refactors/JavaScriptModernizer.js';

export class ToolHandlers {
  // Java重构相关处理器
  private javaAnalyzer: JavaRefactorAnalyzer;
  private springBootAnalyzer: SpringBootRefactorAnalyzer;
  private mavenExecutor: MavenExecutor;
  private fileAnalyzer: FileAnalyzer;
  private fileRefactor: FileRefactor;
  private java8Optimizer: SimpleJava8Optimizer;
  private autoRefactor: AutoRefactorLargeMethod;
  private serviceSplitter: ServiceSplitter;
  private serviceInterfaceGenerator: ServiceInterfaceGenerator;
  private crossFileUpdater: CrossFileReferenceUpdater;
  private packageMover: PackageMover;
  private magicValueExtractor: MagicValueExtractor;
  private enumExtractor: EnumExtractor;
  private springBootOptimizer: SpringBootAnnotationOptimizer;
  private parameterObjectRefactor: ParameterObjectRefactor;
  private fieldEncapsulationRefactor: FieldEncapsulationRefactor;
  private abstractInterfaceExtractor: AbstractInterfaceExtractor;
  private designPatternRefactor: DesignPatternRefactor;
  private builderPatternRefactor: BuilderPatternRefactor;
  private inheritanceRefactor: InheritanceRefactor;
  private inlineRefactor: InlineRefactor;
  private conditionalRefactor: ConditionalRefactor;
  private exceptionRefactor: ExceptionRefactor;
  private springBootConfigRefactor: SpringBootConfigRefactor;

  // 前端重构相关处理器
  private reactRefactor: ReactRefactor;
  private vueRefactor: VueRefactor;
  private cssRefactor: CSSRefactor;
  private jsModernizer: JavaScriptModernizer;
  private aiIntegration: AIIntegration;

  constructor() {
    this.javaAnalyzer = new JavaRefactorAnalyzer();
    this.springBootAnalyzer = new SpringBootRefactorAnalyzer();
    this.mavenExecutor = new MavenExecutor();
    this.fileAnalyzer = new FileAnalyzer();
    this.fileRefactor = new FileRefactor();
    this.java8Optimizer = new SimpleJava8Optimizer();
    this.autoRefactor = new AutoRefactorLargeMethod();
    this.serviceSplitter = new ServiceSplitter();
    this.serviceInterfaceGenerator = new ServiceInterfaceGenerator();
    this.crossFileUpdater = new CrossFileReferenceUpdater();
    this.aiIntegration = new AIIntegration();
    this.packageMover = new PackageMover();
    this.magicValueExtractor = new MagicValueExtractor();
    this.enumExtractor = new EnumExtractor();
    this.springBootOptimizer = new SpringBootAnnotationOptimizer();
    this.parameterObjectRefactor = new ParameterObjectRefactor();
    this.fieldEncapsulationRefactor = new FieldEncapsulationRefactor();
    this.abstractInterfaceExtractor = new AbstractInterfaceExtractor();
    this.designPatternRefactor = new DesignPatternRefactor();
    this.builderPatternRefactor = new BuilderPatternRefactor();
    this.inheritanceRefactor = new InheritanceRefactor();
    this.inlineRefactor = new InlineRefactor();
    this.conditionalRefactor = new ConditionalRefactor();
    this.exceptionRefactor = new ExceptionRefactor();
    this.springBootConfigRefactor = new SpringBootConfigRefactor();
    
    // 初始化前端重构处理器
    this.reactRefactor = new ReactRefactor();
    this.vueRefactor = new VueRefactor();
    this.cssRefactor = new CSSRefactor();
    this.jsModernizer = new JavaScriptModernizer();
  }

  async analyzeJavaFile(filePath: string, rules?: any) {
    return await this.javaAnalyzer.analyzeFile(filePath, rules);
  }

  async analyzeSpringBootProject(projectPath: string) {
    return await this.springBootAnalyzer.analyzeProject(projectPath);
  }

  async refactorLargeFile(filePath: string, strategy: string) {
    // 这个功能现在分散在各个具体的重构器中
    throw new Error('refactor_large_file功能已重构为具体的重构方法，请使用具体的重构工具');
  }

  async refactorLargeMethod(filePath: string, methodName: string, strategy: string) {
    // 🚨 EMERGENCY DISABLED: 使用安全的智能分析器替代破坏性重构
    console.error(`[ToolHandlers] 紧急禁用：refactorLargeMethod改为使用智能分析器`);
    
    const { SmartBatchExtractor } = await import('../refactors/SmartBatchExtractor.js');
    const extractor = new SmartBatchExtractor();
    
    const analysisResult = await extractor.suggestExtractions(filePath, methodName, 80);
    
    return {
      success: analysisResult.success,
      message: `⚠️ 安全重构模式：${analysisResult.message}`,
      filesModified: [],
      suggestions: analysisResult.suggestions,
      errors: analysisResult.errors
    };
  }

  async optimizeJava8Features(filePath: string, features?: string[]) {
    return await this.java8Optimizer.optimizeFile(filePath, features);
  }

  async checkSingleResponsibility(filePath: string) {
    // 这个功能现在在JavaRefactorAnalyzer中
    return await this.javaAnalyzer.analyzeFile(filePath);
  }

  async cleanUnusedCode(projectPath: string, aggressive: boolean = false) {
    // 这个功能需要单独实现
    throw new Error('clean_unused_code功能需要单独实现');
  }

  async mavenCompile(projectPath: string, clean: boolean = false) {
    return await this.mavenExecutor.compile(projectPath, clean);
  }

  async mavenTest(projectPath: string, skipTests: boolean = false) {
    return await this.mavenExecutor.test(projectPath, skipTests);
  }

  async suggestSpringBootImprovements(projectPath: string) {
    return await this.springBootAnalyzer.suggestImprovements(projectPath);
  }

  async splitLargeService(filePath: string, splitStrategy: string) {
    return await this.serviceSplitter.splitLargeService(filePath, splitStrategy);
  }

  async generateServiceInterface(filePath: string, interfaceName?: string, implName?: string) {
    return await this.serviceInterfaceGenerator.generateInterface(filePath, interfaceName, implName);
  }

  async updateCrossFileReferences(targetFilePath: string, projectPath: string, methodChanges?: any[]) {
    return await this.crossFileUpdater.updateReferences(targetFilePath, projectPath, methodChanges);
  }

  async movePackage(sourceFilePath: string, targetPackage: string, projectPath: string, updateReferences: boolean) {
    return await this.packageMover.moveToPackage(sourceFilePath, targetPackage, projectPath, updateReferences);
  }

  async introduceParameterObject(filePath: string, methodName: string, parameterObjectName: string, projectPath: string, minParameterCount: number) {
    return await this.parameterObjectRefactor.introduceParameterObject(filePath, methodName, parameterObjectName, projectPath, minParameterCount);
  }

  async encapsulateFields(filePath: string, projectPath: string, includeProtected: boolean, generateSetters: boolean) {
    return await this.fieldEncapsulationRefactor.encapsulateFields(filePath, projectPath, includeProtected, generateSetters);
  }

  async refactorToStrategy(filePath: string, methodName: string, strategyInterfaceName: string, projectPath: string) {
    return await this.designPatternRefactor.refactorToStrategy(filePath, methodName, strategyInterfaceName, projectPath);
  }

  async extractInterface(classFiles: string[], interfaceName: string, projectPath: string, outputDir?: string) {
    return await this.abstractInterfaceExtractor.extractInterface(classFiles, interfaceName, projectPath, outputDir);
  }

  async introduceBuilder(filePath: string, minParameterCount: number, builderClassName?: string) {
    return await this.builderPatternRefactor.introduceBuilder(filePath, minParameterCount, builderClassName);
  }

  async renameClass(filePath: string, oldClassName: string, newClassName: string, projectPath: string) {
    return await this.fileRefactor.renameClass(filePath, oldClassName, newClassName, projectPath);
  }

  async renameMethod(filePath: string, className: string, oldMethodName: string, newMethodName: string, projectPath: string) {
    return await this.fileRefactor.renameMethod(filePath, className, oldMethodName, newMethodName, projectPath);
  }

  async extractMethod(filePath: string, startLine: number, endLine: number, newMethodName: string, returnType?: string) {
    return await this.fileRefactor.extractMethod(filePath, startLine, endLine, newMethodName, returnType);
  }

  async autoRefactorLargeMethod(filePath: string, methodName: string, maxLines: number = 80) {
    // 🚨 紧急重新禁用 - 自动重构功能存在严重的代码破坏风险
    console.error(`[ToolHandlers] ⛔ 紧急禁用：autoRefactorLargeMethod因代码破坏风险被重新禁用`);
    
    // 使用安全的智能分析器替代
    const { SmartBatchExtractor } = await import('../refactors/SmartBatchExtractor.js');
    const extractor = new SmartBatchExtractor();
    
    const analysisResult = await extractor.suggestExtractions(filePath, methodName, maxLines);
    
    return {
      success: analysisResult.success,
      message: '🚨 **安全模式重新激活** - 自动重构功能已紧急禁用\n\n' +
               '❌ **严重问题**：自动重构功能破坏了代码结构\n' +
               '🛡️ **安全措施**：已恢复到安全的智能分析模式\n\n' +
               '📋 **分析结果**：\n' + analysisResult.message + '\n\n' +
               (analysisResult.suggestions.length > 0 ? 
                 '💡 **安全重构建议**：\n' + analysisResult.suggestions.join('\n') + '\n\n' : '') +
               '⚠️ **重要提醒**：\n' +
               '- 使用 extract_method 工具进行**手动**安全重构\n' +
               '- 每次只提取一个小的逻辑块\n' +
               '- 提取后立即验证代码编译\n' +
               '- 自动重构功能需要进一步开发才能安全使用\n\n' +
               '🔧 **推荐步骤**：\n' +
               '1. 先用 analyze_java_file 分析文件\n' +
               '2. 识别最简单的可提取代码块\n' +
               '3. 使用 extract_method 逐一提取\n' +
               '4. 每次提取后测试编译',
      filesModified: [],
      extractedMethods: analysisResult.extractedMethods,
      errors: ['自动重构功能因安全问题被禁用'],
      validationResults: {
        syntaxValid: true, // 分析模式不会破坏代码
        compilationTested: false
      }
    };
  }

  async extractMagicValues(filePath: string, autoFix: boolean = false) {
    return await this.magicValueExtractor.extractMagicValues(filePath, autoFix);
  }

  async suggestEnums(filePath: string, autoCreate: boolean = false) {
    return await this.enumExtractor.analyzeForEnums(filePath, autoCreate);
  }

  async optimizeSpringBootAnnotations(filePath: string) {
    return await this.springBootOptimizer.optimizeToAnnotationBased(filePath);
  }

  // ============ 前端重构方法 ============

  // React重构方法
  async convertReactClassToHooks(filePath: string) {
    return await this.reactRefactor.convertClassToHooks(filePath);
  }

  async extractCustomHook(filePath: string) {
    return await this.reactRefactor.extractCustomHook(filePath);
  }

  async optimizeReactPerformance(filePath: string) {
    return await this.reactRefactor.optimizeReactPerformance(filePath);
  }

  // Vue重构方法
  async convertVueToCompositionAPI(filePath: string) {
    return await this.vueRefactor.convertToCompositionAPI(filePath);
  }

  async extractVueComposables(filePath: string) {
    return await this.vueRefactor.extractComposables(filePath);
  }

  async optimizeVuePerformance(filePath: string) {
    return await this.vueRefactor.optimizeVuePerformance(filePath);
  }

  // CSS重构方法
  async convertCSSBEM(filePath: string) {
    return await this.cssRefactor.convertToBEM(filePath);
  }

  async convertCSSToCSSInJS(filePath: string) {
    return await this.cssRefactor.convertToCSSInJS(filePath);
  }

  async optimizeSCSS(filePath: string) {
    return await this.cssRefactor.optimizeSCSS(filePath);
  }

  async optimizeCSSPerformance(filePath: string) {
    return await this.cssRefactor.optimizeCSSPerformance(filePath);
  }

  // JavaScript现代化方法
  async modernizeJavaScriptToES6(filePath: string) {
    return await this.jsModernizer.modernizeToES6Plus(filePath);
  }

  async convertPromiseToAsyncAwait(filePath: string) {
    return await this.jsModernizer.convertToAsyncAwait(filePath);
  }

  async optimizeJavaScriptPerformance(filePath: string) {
    return await this.jsModernizer.optimizeJavaScriptPerformance(filePath);
  }

  // AI集成方法
  async aiCodeReview(filePath: string, aiProvider: 'lingma' | 'trae', reviewType: string = 'code_review') {
    try {
      if (aiProvider === 'lingma') {
        return await this.aiIntegration.reviewWithLingma(filePath, reviewType);
      } else if (aiProvider === 'trae') {
        return await this.aiIntegration.reviewWithTrae(filePath, reviewType);
      } else {
        throw new Error(`不支持的AI服务提供商: ${aiProvider}`);
      }
    } catch (error) {
      return {
        success: false,
        message: `AI代码审查失败: ${error}`,
        suggestions: [],
        refactorPlans: [],
        issues: []
      };
    }
  }

  async aiRefactorPlan(targetPath: string, planType: string, aiProvider: 'lingma' | 'trae') {
    try {
      // 基于AI分析生成重构计划
      const reviewResult = await this.aiCodeReview(targetPath, aiProvider, 'refactor_suggestion');
      
      return {
        success: reviewResult.success,
        message: `AI重构计划 (${planType}) 生成完成`,
        plan: {
          type: planType,
          steps: reviewResult.refactorPlans,
          estimatedTime: `${reviewResult.refactorPlans.length * 15} 分钟`,
          riskLevel: this.calculateRiskLevel(reviewResult.refactorPlans),
          priority: this.prioritizeSteps(reviewResult.refactorPlans)
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `AI重构计划生成失败: ${error}`,
        plan: null
      };
    }
  }

  private calculateRiskLevel(plans: any[]): string {
    const highRiskCount = plans.filter(p => p.priority === 'high').length;
    if (highRiskCount > 3) return 'high';
    if (highRiskCount > 1) return 'medium';
    return 'low';
  }

  private prioritizeSteps(plans: any[]): any[] {
    return plans.sort((a, b) => {
      const priorityOrder: { [key: string]: number } = { high: 3, medium: 2, low: 1 };
      return (priorityOrder[b.priority] || 1) - (priorityOrder[a.priority] || 1);
    });
  }
}